﻿using SuperMap.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using Ycjw.PipeLine.Map.Basic;
using Ycjw.PipeLine.Map.Basic.SuperMap;
using Ycjw.PipeLine.Scenes;

namespace Ycjw.PipeLine
{
    public partial class FormMainRibbon : Sunny.UI.UIForm, IMessageInterface
    {
        static FormMainRibbon m_Instance;
        SceneSetting m_SceneSetting;
        SceneMeasure m_SceneMeasure;
        SceneEntitySelect m_SceneEntitySelect;
        public static FormMainRibbon Instance
        {
            get
            {
                if(m_Instance == null)
                {
                    m_Instance = new FormMainRibbon();
                }
                return m_Instance;
            }
        }
        FormMainRibbon()
        {
            SplashForm.Instance.TopMost = true;
            SplashForm.Instance.TopLevel = true;
            SplashForm.Instance.Show();
            Application.DoEvents();
            SplashForm.Instance.BringToFront();
            this.IsMdiContainer = true;
            InitializeComponent();
            try
            {
                this.Left = SplashForm.Instance.Left;
                this.Top = SplashForm.Instance.Top;
                this.Size = SplashForm.Instance.Size;
            }
            catch(Exception ex)
            {
                Commons.LogHelper.Error(ex.Message);
            }
            this.dockPanel.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.SystemMdi;
        }

        void LoadSceneLater()
        {
            SplashForm.Instance.SetMessage("初始化场景......");
            SceneAdapter.Instance.LoadSceneControl(dockPanel);
            Task.Factory.StartNew(() =>
            {
                System.Threading.Thread.Sleep(500);
            }).ContinueWith((t) => {
                SplashForm.Instance.SetMessage("场景初始化完成......");
                RibbonMenuRegister.Instance.SetDockPanel(this.dockPanel);

                UnRegister();

                m_SceneSetting = new SceneSetting(SceneAdapter.Instance.SceneControl,this);
                m_SceneMeasure = new SceneMeasure(SceneAdapter.Instance.SceneControl,this);
                m_SceneEntitySelect = new SceneEntitySelect(SceneAdapter.Instance.SceneControl,this);

                SceneAdapter.Instance.NewOpenEvent += WorkSpace_NewOpenEvent;

                //打开最后一次打开的工作空间
                var lastPath = Commons.SerializeHelper.IniHelper.Read(Commons.SerializeHelper.IniHelper.KEY_LAST_WORKSPACE_PATH);
                if (!string.IsNullOrEmpty(lastPath))
                {
                    SplashForm.Instance.SetMessage("加载上一次场景......");
                    SceneAdapter.Instance.OpenWorkSpace(lastPath);
                }
                System.Threading.Thread.Sleep(500);
                SplashForm.Instance.CloseIt = true;
                WindowState = FormWindowState.Maximized;
                this.BringToFront();

            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void WorkSpace_NewOpenEvent(SceneControl sceneControl)
        {
            ///???
            this.m_SceneMeasure.SceneControl = sceneControl;
            this.m_SceneSetting.SceneControl = sceneControl;
            var lookAt = sceneControl.Scene.LookAt;
            if (!sceneControl.Scene.LookAt.IsValid) return;
            var lookAtKeys = new List<string>() 
            {
                "Longitude","Latitude","Tilt","Range","Altitude","Heading"
            };
            var lookAtValues = new List<object>() 
            {
                lookAt.Longitude,lookAt.Latitude,lookAt.Tilt,lookAt.Range,lookAt.Altitude,lookAt.Heading
            };
            Commons.SerializeHelper.IniHelper.WriteLookAt(lookAtKeys.ToArray(), lookAtValues.ToArray());
        }
        void UnRegister()
        {
            foreach(var tab in this.ribbonMain.Tabs)
            {
                foreach(var panel in tab.Panels)
                {
                    foreach(var item in panel.Items)
                    {
                        if(item is RibbonButton)
                        {
                            var btn = item as RibbonButton;
                            btn.Click += new System.EventHandler((sender,e)=> {
                                UnregisterImpl();
                            });
                        }
                    }
                }
            }
        }

        void UnregisterImpl()
        {
            if (!SceneAdapter.Instance.SceneControl.IsDisposed)
            {
                SceneAdapter.Instance.SceneControl.Action = Action3D.Pan;
            }
            foreach (var soi in SceneOperInterface.AllSceneOperInterface.Values)
            {
                soi.UnRegister();
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            void SetText()
            {
                this.Text = "云创经纬管线管理地理信息系统";
            }
            void SetIcon()
            {
                var iconPath = Commons.Paths.ApplicationResourcesDir + "//favorite.ico";
                this.Icon = new System.Drawing.Icon(iconPath);
            }
            void SetTitleBgColor()
            {
                this.TitleColor = System.Drawing.Color.Black;
            }
            SetTitleBgColor();
            SetText();
            SetIcon();
            RibbonMenuRegister.Instance.RegisterByConfig(this.ribbonMain);
            RibbonMenuRegister.Instance.AddTabs(this.ribbonMain);

            this.ribbonButtonOpenWorkSpace.Click += RibbonButton_OpenWorkSpace_Click;
            this.ribbonButtonCloseWorkSpace.Click += RibbonButtonCloseWorkSpace_Click;

            this.ribbonButtonFullScreen.Click += RibbonButtonFullScreen_Click;
            this.ribbonButtonRealTime.Click += RibbonButtonRealTime_Click;
            this.ribbonButtonExit.Click += RibbonButtonExit_Click;

            LoadSceneLater();
            base.OnLoad(e);
        }

        private void RibbonButtonRealTime_Click(object sender, EventArgs e)
        {
            SceneAdapter.Instance.RealTime();
        }

        private void RibbonButtonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void RibbonButtonFullScreen_Click(object sender, EventArgs e)
        {
            SceneAdapter.Instance.FullScreen();
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (Sunny.UI.UIMessageDialog.ShowAskDialog(this, "确认退出系统吗？",Sunny.UI.UIStyle.Red))
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }
        private void RibbonButtonCloseWorkSpace_Click(object sender, EventArgs e)
        {
            SceneAdapter.Instance.CloseWorkSpace();
        }

        private void RibbonButton_OpenWorkSpace_Click(object sender, EventArgs e)
        {
            SceneAdapter.Instance.OpenWorkSpace();
        }

        protected override void OnActivated(EventArgs e)
        {
            FormCollection fc = Application.OpenForms;
            foreach (Form f in fc) {
                if (f == this) continue;
                else if (f.GetType() == typeof(ToolWindowExtend)) continue;
                else if (f.GetType() == typeof(LayersTreeEx)) continue;
                else if (f.TopLevel && f.TopMost) continue;
                else if (!f.Visible) continue;
                else
                {
                    if (f.InvokeRequired)
                    {
                        f.Invoke(new System.Action(() =>
                        {
                            f.BringToFront();
                        }));
                    }
                    else
                    {
                        f.BringToFront();
                    }
                }
            }

            base.OnActivated(e);
        }

        #region 消息显示
        public void ShowInfo(string msg)
        {
            ShowMessage(msg,"Info");
        }
        public void ShowError(string msg)
        {
            ShowMessage(msg, "Error");
        }
        public void ShowWarn(string msg)
        {
            ShowMessage(msg, "Warn");
        }
        void ShowMessage(string Message, string type)
        {
            this.Invoke(new System.Action(() => {
                if (type == "Error")
                {
                    this.uiLabelMessage.ForeColor = System.Drawing.Color.Red;
                }
                else if (type == "Info")
                {
                    this.uiLabelMessage.ForeColor = System.Drawing.Color.Black;
                }
                else if (type == "Warn")
                {
                    this.uiLabelMessage.ForeColor = System.Drawing.Color.Gold;
                }
                this.uiLabelMessage.Text = Message;
            }));
        }
        #endregion
    }
}
